/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kosongkosong.scheduler;

import com.kosongkosong.model.Match;
import com.kosongkosong.model.Phase;
import com.kosongkosong.service.DataService;
import com.kosongkosong.utils.UrlUtils;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.cyberneko.html.parsers.DOMParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static com.kosongkosong.scheduler.UrlConstants.*;

/**
 *
 * @author ifnu
 */
@Controller
public class ScheduleParserScheduler {

    @Autowired private DataService dataService;

    @RequestMapping(value = "/parse-schedule", method = RequestMethod.GET)
    public void v(HttpServletResponse response) throws Exception {
        response.getOutputStream().close();
    }
    
    @RequestMapping(value = "/p-schedule", method = RequestMethod.GET)
    public void parseSchedule(HttpServletResponse response) throws Exception {

        //fetch url
        String schedule = UrlUtils.fetchUrl(FIXTURE_GROUP);
        //parse using nekohtml
        List<Match> matches = parseSchedule(schedule);
        //save schedule matches
        for (Match m : matches) {
            if(dataService.getMatch(m.getId())==null){
                dataService.save(m);
            } else {
                dataService.update(m);
            }
        }
        response.getOutputStream().close();
    }

    List<Match> parseSchedule(String schedule) {
        List<Match> matches = new ArrayList<Match>();
        try {

            DOMParser parser = new DOMParser();
            parser.parse(new InputSource(new StringReader(schedule)));
            //get main page URL
            Document d = parser.getDocument();
            NodeList nodeList = d.getElementsByTagName("div");

            //get group
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NamedNodeMap map = node.getAttributes();
                if (map != null) {
                    Node classAttribute = map.getNamedItem("class");
                    if (classAttribute != null) {
                        String classAttributeValue = classAttribute.getNodeValue();
                        //group name
                        if (classAttributeValue != null && classAttributeValue.equals("ind tL")) {
                            NodeList content = node.getChildNodes();
                            String date = null;
                            String time = null;
                            String groupName = null;
                            String stage = null;
                            for(int j=0;j<content.getLength();j++){
                                Node contentChild = content.item(j);
                                Match m = null;
                                if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("span")
                                        && contentChild.getTextContent().startsWith("Group")){
                                    groupName = getGroupName(contentChild.getTextContent());
                                    stage = "gp";
                                } else if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("span")
                                        && contentChild.getTextContent().startsWith("Second")){
                                    stage = "sr";
                                } else if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("span")
                                        && contentChild.getTextContent().startsWith("Quarter")){
                                    stage = "qf";
                                } else if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("span")
                                        && contentChild.getTextContent().startsWith("Semi")){
                                    stage = "sf";
                                } else if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("span")
                                        && contentChild.getTextContent().startsWith("Third")){
                                    stage = "tp";
                                } else if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("span")
                                        && contentChild.getTextContent().startsWith("Final")){
                                    stage = "f";
                                } else if(contentChild.getLocalName()==null
                                        && contentChild.getNextSibling()!=null
                                        && contentChild.getNextSibling().getLocalName()!=null
                                        && contentChild.getNextSibling().getLocalName().equalsIgnoreCase("br")){
                                    date = contentChild.getTextContent();
                                } else if(contentChild.getLocalName()!=null
                                        && contentChild.getLocalName().equalsIgnoreCase("a")){
                                    //parse team a,b and hour
                                    m = new Match();
                                    time = getTime(contentChild.getTextContent());
                                    m.setDate(getDate(date + " " + time));
                                    if(stage!=null && Phase.gp.name().equals(stage)){
                                        m.setGroup(groupName);
                                    }
                                    m.setStage(stage);
                                    String[] teams = getTeams(contentChild.getTextContent());
                                    m.setTeamA(teams[0]);
                                    m.setTeamB(teams[1]);

                                    //get match id
                                    Node matchIdNode = contentChild.getAttributes().getNamedItem("href");
                                    if(matchIdNode!=null){
                                        m.setId(getMatchId(matchIdNode.getNodeValue()));
                                    }
                                    matches.add(m);
                                }
                            }
                            break;
                        }
                    }
                }
            }

        } catch (SAXException ex) {
            Logger.getLogger(HeadlineParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HeadlineParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return matches;
    }

    Date getDate(String date){
        try {
            return new SimpleDateFormat("yyyy MMM dd hh:mm a").parse("2010 "+date);
        } catch (ParseException ex) {
//            Logger.getLogger(ScheduleParserScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    String getGroupName(String groupName){
        return groupName.substring(14,groupName.length());
    }

    String getMatchId(String matchIdLink){
        int ampIndex = matchIdLink.indexOf("&");
        int equalIndex = matchIdLink.indexOf("=");
        return matchIdLink.substring(equalIndex+1,ampIndex);
    }

    String getTime(String text){
        int dashIndex = text.indexOf("-");
        return text.substring(0,dashIndex).trim();
    }

    String[] getTeams(String text){
        int vsIndex = text.indexOf("vs");
        int dashIndex = text.indexOf("-");
        return new String[]{text.substring(dashIndex+1,vsIndex).trim(),text.substring(vsIndex + 2,text.length()).trim()};
    }

}
